package com.nosweattechnet.server;

import java.util.concurrent.ExecutionException;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import com.nosweattechnet.datatypes.Item;

//Allows the app to retrieve an Item given its uuid
public class ItemIDAsyncTask extends CommunicatorAsyncTask {
	//Constants specifed in the php script
	private BasicNameValuePair tag=new BasicNameValuePair("tag","getItemById");
	private String itemIDString="item_uuid";
	
	//Initializes the Communicator then adds the required tag, which specified the function, and adds the desired id, using the constant as the Name.
	public ItemIDAsyncTask(String itemid) {
		super();
		super.addNameValuePair(tag);
		super.addNameValuePair(new BasicNameValuePair(itemIDString,itemid));
	}
	
	//Parses the resulting JSONArray to an Item
	//IF NO JSONARRAY IS RETURNED, I.E. NO ITEM HAS THE SPECIFIED ID, THEN NULL IS RETURNED
	public Item getItem() throws InterruptedException, ExecutionException{
		JSONArray jarr=this.get();
		if(jarr.length()!=1){
			return null;
		}
		Item i=null;
		try {
			i = new Item(jarr.getJSONObject(0));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return i;
	}
}
